<script setup>
import { ref, computed, watchEffect } from 'vue'
import nativeApi from '../../utils/native.js'
import Utility from '@/utils/utility'
import { Overlay } from 'vant'
const show = ref(false)
const showImage = ref([])
const fileNameList = ref([])
const props = defineProps({
  fileUrl: {
    type: String,
    default: '',
  },
  fileName: {
    type: String,
    default: '',
  },
})
const fileList = computed(() => {
  return props.fileUrl.split(',')
})
function getFileNameByFileUrl(url) {
  if (!url) return
  let uploadFileNameStr = url.split('/').pop()
  const fileNameStr = uploadFileNameStr.split('_').slice(1).join('_')
  return decodeURIComponent(fileNameStr)
}
function getFileNames(fileUrl) {
  if (!fileUrl) return
  let fileArr = fileUrl.split(',')
  let fileNames = []
  for (const url of fileArr) {
    const name = getFileNameByFileUrl(url)
    fileNames.push(name)
  }
  return fileNames
}
watchEffect(() => {
  if (!props.fileUrl) return
  fileNameList.value = getFileNames(props.fileUrl)
})
function handlePreview(name, index) {
  // if (isPdf(name)) {
  if (Utility.isNoNeedPreviewFile(name)) {
    nativeApi.jumpExternalLink({
      urlStr: fileList.value[index],
    })
  } else {
    let _domain = Utility.getGatewayDomain()
    let _url = _domain + '/getFile?fileName=' + fileList.value[index]
    showImage.value = [_url]
    show.value = true
  }
}
</script>

<template>
  <div v-if="props.fileUrl">
    <div
      v-for="(item, index) in fileNameList"
      class="file__item"
      @click="handlePreview(item, index)"
      :key="index"
    >
      <i
        class="iconfont"
        :class="
          Utility.isNoNeedPreviewFile(item)
            ? 'icon-pdfwenjianicon'
            : 'icon-tupianicon'
        "
      />
      <span>{{ item }}</span>
    </div>
    <Overlay :show="show" @click="show = false" z-index="99">
      <div class="img__wrapper wrapper">
        <img :src="showImage" alt="" />
      </div>
    </Overlay>
  </div>
</template>

<style lang="scss" scoped>
.file__item {
  display: flex;
  align-items: center;
  word-break: break-all;
  span {
    margin-left: 4px;
  }
}
:deep {
  .van-overlay {
    display: flex;
    align-items: center;
    justify-content: center;
    .wrapper img {
      display: block;
      width: 100%;
      height: 100%;
    }
  }
}
</style>
